package cn.nebula.util.lucene.helloworld;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import cn.nebula.util.lucene.utils.File2DocumentUtils;


public class HelloWorld {

	String filePath = "E:\\Eclipse\\workplace(gzakoa)\\aform\\src\\main\\java\\cn\\nebula\\util\\lucene\\luceneDatasource\\IndexWriter addDocument's a javadoc .txt";

	String indexPath = "E:\\Eclipse\\workplace(gzakoa)\\aform\\src\\main\\java\\cn\\nebula\\util\\lucene\\luceneIndex";

	Analyzer analyzer = new StandardAnalyzer();
	
	public static void main(String[] args) throws Exception {
		HelloWorld test= new HelloWorld();
		test.createIndex();
		test.search();
	}

	public void createIndex() throws Exception {
		Document doc = File2DocumentUtils.file2Document(filePath);

		IndexWriter indexWriter = new IndexWriter(indexPath, analyzer, true,
				MaxFieldLength.LIMITED);
		indexWriter.addDocument(doc);
		indexWriter.close();
	}

	public void search() throws Exception {
		String queryString = "room";
//		String queryString = "adddocument";

		String[] fields = { "name", "content" };
		QueryParser queryParser = new MultiFieldQueryParser(fields, analyzer);
		Query query = queryParser.parse(queryString);

		IndexSearcher indexSearcher = new IndexSearcher(indexPath);
		Filter filter = null;
		TopDocs topDocs = indexSearcher.search(query, filter, 10000);
		System.out.println("共有【" + topDocs.totalHits + "】条匹配结果");

		for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
			int docSn = scoreDoc.doc; 
			Document doc = indexSearcher.doc(docSn); 
			File2DocumentUtils.printDocumentInfo(doc);
		}
	}
}
